package com.kungfuhacking.wristbandpro.mqtt;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.widget.Toast;

import com.kungfuhacking.wristbandpro.R;
import com.kungfuhacking.wristbandpro.utils.Constant;
import com.kungfuhacking.wristbandpro.utils.LogUtil;

import mqttresource.MqttClient;

/**
 * 检测网络是否可用的广播
 * Created by Aaron on 17/7/19.
 */

public class NetReceiver extends BroadcastReceiver {


    private boolean isAvailable = true;
    SharedPreferences sp;

    @Override
    public void onReceive(Context context, Intent intent) {

        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo mobNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        NetworkInfo wifiNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

        if (!mobNetInfo.isConnected() && !wifiNetInfo.isConnected()) {

            LogUtil.e("tag", getClass().getName() + "网络不可用!!!!!!!!");

            if (isAvailable) {
                isAvailable = false;
                Toast.makeText(context, context.getResources().getString(R.string.net_off), Toast.LENGTH_SHORT).show();
            }

        } else {
            LogUtil.e("tag", getClass().getName() + "网络可用啦~~~~~~");

            isAvailable = true;
            //连接mqtt
            MqttClient mqttClient = MqttManager.getInstance().getMqttClient();


            if (sp == null)
                sp = context.getSharedPreferences(Constant.CONFIG, Context.MODE_PRIVATE);

            if (sp.getBoolean(MqttConstant.INTERVAL_CONNET_MQTT, true))
                if (mqttClient == null || !mqttClient.isConnected())
                    MqttManager.getInstance().getMqttIp(context.getApplicationContext());
        }


    }

}
